package com.vincent.template.commons.validation.validators;

import com.vincent.template.commons.constanst.EnumType;
import com.vincent.template.commons.validation.constraints.MatchEnum;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @Author Vincent Wang
 * @Date 2020/9/3 09:52
 */
public class MatchEnumValidator implements ConstraintValidator<MatchEnum, String> {

    private boolean required;
    private EnumType type;

    @Override
    public void initialize(MatchEnum constraintAnnotation) {
        required = constraintAnnotation.required();
        type = constraintAnnotation.type();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isBlank(value)) {
            return !required;
        }
        return type.getCheck().exists(value);
    }
}
